package com.tangyee.home_knowledge.acticity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tangyee.R;
import com.tangyee.home_knowledge.adapter.KnowsAdapter;
import com.tangyee.home_knowledge.bean.KnowledgeItem;
import com.tangyee.home_knowledge.util.ConstantUtil;
import com.tangyee.home_knowledge.util.HttpUtil;
import com.tangyee.refreshloadlistview.SimpleFooter;
import com.tangyee.refreshloadlistview.SimpleHeader;
import com.tangyee.refreshloadlistview.ZrcListView;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class KonwledgeActivity extends AppCompatActivity implements View.OnClickListener{
    private ZrcListView listView;
    private Handler handler;
    private Handler httpHandler;
    private List<KnowledgeItem> currentKnowledgeItem;
    private List<KnowledgeItem> httpGetKnowledgeItem;
//  -1-   private KnowledgeListViewAdapter adapter;
//  -2-  private KnowsListViewAdapter adapter;
    private KnowsAdapter adapter;

    // 分页的大小，即每次请求得到的知识 item 数
    private int pageSize = 8;
    // 网络请求的分页从 1 开始。用这个参数控制每次请求的数据都是新的
    private int page = 1;
    // 是否已经全部更新完
    private boolean isAll = false;
    // 请求成功
    private static final int SUCCESS = 1;
    // 请求失败
    private static final int FALL = 2;
    // 请求的数据已到底
    private static final int FINISH = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_home_knowledge);

        init();

        findViewById(R.id.knowsbackMain).setOnClickListener(this);
        findViewById(R.id.knowsToSort).setOnClickListener(this);
        findViewById(R.id.Knows_To_Search).setOnClickListener(this);

        // 下拉刷新时间回调(可选)
        listView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                refresh();
            }
        });
        // 加载更多事件回调（可选）
        listView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                loadMore();
            }
        });
        // 主动下拉刷新
        listView.refresh();
        // item 的点击事件
        listView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                Intent intent = new Intent(KonwledgeActivity.this, KnowledgeDetailActicity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("knowID", currentKnowledgeItem.get(position).getKnowID());
                bundle.putString("title", currentKnowledgeItem.get(position).getTitle());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.knowsbackMain:
                finish();
                break;
            case R.id.knowsToSort:
                Intent sort = new Intent(KonwledgeActivity.this, KnowledgeSortActivity.class);
                startActivity(sort);
                break;
            case R.id.Knows_To_Search:
                Intent intent = new Intent(KonwledgeActivity.this, SearchKnowledgeActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void init(){
        listView = (ZrcListView) findViewById(R.id.KnowsListView);
        handler = new Handler();
        currentKnowledgeItem = new ArrayList<>();
        httpGetKnowledgeItem = new ArrayList<>();

        // 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(this);
        header.setTextColor(0xff0066aa);
        header.setCircleColor(0xff33bbee);
        listView.setHeadable(header);
        // 设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(this);
        footer.setCircleColor(0xff33bbee);
        listView.setFootable(footer);
        // 设置列表项出现动画（可选）
        listView.setItemAnimForTopIn(R.anim.topitem_in);
        listView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 初始化适配器
        adapter = new KnowsAdapter(this, R.layout.layout_home_knowledge_listitem, currentKnowledgeItem);
//      -2-  adapter = new KnowsListViewAdapter(currentKnowledgeItem);
//      -1-  adapter = new KnowledgeListViewAdapter(KonwledgeActivity.this, R.layout.layout_home_knowledge_listitem, currentKnowledgeItem);
        listView.setAdapter(adapter);

        // 初始化 http 请求的参数
        pageSize = 8;
        page = 1;
        isAll = false;
    }

    // 下拉刷新
    private void refresh(){
        handler.postDelayed(new Runnable() {
            @SuppressLint("HandlerLeak")
            @Override
            public void run() {

                // isAll 是用来标识是不是所有数据都加载完了，是的话，就不会将 adapter 的数据清空
                //if (!isAll) {
                    // -1-  -2-  currentKnowledgeItem = new ArrayList<>();
                    // 3
                    //adapter.clear();
                //}
                loadKnowledge();
                httpHandler = new Handler(){
                    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
                    @Override
                    public void handleMessage(Message msg) {
                        switch (msg.what){
                            case SUCCESS:
                                // -1-  -2-  currentKnowledgeItem.addAll(httpGetKnowledgeItem);
                                //// 3
                                adapter.clear();
                                adapter.addAll(httpGetKnowledgeItem);
                                // -1-  -2-  adapter.setKnowledgeItemList(currentKnowledgeItem);
                                // 3
                                adapter.notifyDataSetChanged();
                                listView.setRefreshSuccess("加载成功"); // 通知加载成功
                                listView.startLoadMore(); // 开启LoadMore功能
                                page++;
                                break;
                            case FALL:
                                listView.setRefreshFail("加载失败");
                                break;
                            case FINISH:
                                // -1-  -2-  currentKnowledgeItem.addAll(httpGetKnowledgeItem);
                                // -1-  -2-  adapter.setKnowledgeItemList(currentKnowledgeItem);
                                // 3
                                if (!isAll) {
                                    adapter.clear();
                                    adapter.addAll(httpGetKnowledgeItem);
                                    adapter.notifyDataSetChanged();
                                    listView.setRefreshSuccess("加载成功");
                                }else {
                                    listView.setRefreshSuccess("没有更多的数据了");
                                }
                                listView.stopLoadMore(); // 这里要设置不能上拉加载了
                                isAll = true;
                                break;
                        }
                    }
                };
            }
        }, 0);
    }

    // 上拉加载
    private void loadMore(){
        handler.postDelayed(new Runnable() {
            @SuppressLint("HandlerLeak")
            @Override
            public void run() {

                loadKnowledge();
                httpHandler = new Handler(){
                    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
                    @Override
                    public void handleMessage(Message msg) {
                        switch (msg.what){
                            case SUCCESS:
                                // -1-  -2-  currentKnowledgeItem.addAll(httpGetKnowledgeItem);
                                // -1-  -2-  adapter.setKnowledgeItemList(currentKnowledgeItem);
                                // 3
                                adapter.addAll(httpGetKnowledgeItem);
                                adapter.notifyDataSetChanged();
                                // 此次加载成功，这里一定要声明，否则会误以为还没有成功，一直等待下去
                                listView.setLoadMoreSuccess();
                                page++;
                                break;
                            case FALL:
                                break;
                            case FINISH:
                                // -1-  -2-  currentKnowledgeItem.addAll(httpGetKnowledgeItem);
                                // -1-  -2-  adapter.setKnowledgeItemList(currentKnowledgeItem);
                                // 3
                                adapter.addAll(httpGetKnowledgeItem);
                                adapter.notifyDataSetChanged();
                                listView.stopLoadMore();
                                isAll = true;
                                break;
                        }
                    }
                };
            }
        }, 0);
    }

    /**
     * 网络请求，加载知识 item
     */
    private void loadKnowledge(){
        // 设置 get 请求的参数（page, pageSize）
        LinkedHashMap<String, String> params = new LinkedHashMap<>();
        params.put("page", page + "");
        params.put("pagesize", pageSize + "");

        HttpUtil.sendRequest(ConstantUtil.knowledgeURL, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = httpHandler.obtainMessage();
                message.what = FALL;
                httpHandler.sendMessage(message);
            }

            /**
             * 这里不在 UI 线程里面
             * @param call
             * @param response
             * @throws IOException
             */
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 使用轻量级的Gson解析得到的json
                String responseData = response.body().string();
                Type listType = new TypeToken<List<KnowledgeItem>>(){}.getType();
                Gson gson = new Gson();
                httpGetKnowledgeItem = gson.fromJson(responseData, listType);

                // 如果此次请求得到的数据没有达到像请求的数据的个数，则说明服务端没有更多的数据了
                if (httpGetKnowledgeItem.size() == pageSize) {
                    // 通知加载成功
                    Message message = httpHandler.obtainMessage();
                    message.what = SUCCESS;
                    httpHandler.sendMessage(message);
                }else {
                    // 通知数据已到底
                    Message message = httpHandler.obtainMessage();
                    message.what = FINISH;
                    httpHandler.sendMessage(message);
                }


                // 由于上拉刷新和下拉加载的动作不一样，导致用下面的UI 线程不太方便来执行这两种动作，所以选择了用 Handler
//                // 在这里将请求到的数据用于更新 UI
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        currentKnowledgeItem.addAll(httpGetKnowledgeItem);
//                        adapter.setKnowledgeItemList(currentKnowledgeItem);
//                        adapter.notifyDataSetChanged();
//                        listView.setRefreshSuccess("加载成功"); // 通知加载成功
//                        listView.startLoadMore(); // 开启LoadingMore功能
//                    }
//                });
//                page++;
            }
        });
    }

}
